/**
 * @param colKey 字段类型
 * @param maxLength 最大长度
 */

// 表格字符编辑单元格
import { Component } from "react";
import FormControl from 'bee-form-control';
import 'bee-form-control/build/FormControl.css';
import './StringEditCell.less';
import { vendorsDanger as danger } from "../../../../utils/config";
class StringEditCell extends Component {
    constructor(props, context) {
        super(props);
        this.state = {
            value: props.value, // 输入框内容
            isFormFocus: false, // 是否获取焦点
            maxInputStr: props.maxLength, // 最多输入个数
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({ value: nextProps.value });
    }

    handleChange = (value) => {
        let textOverflowIndex = this.state.maxInputStr;
        let timedValue = this.props.colKey === "code" ? value.replace(/[^\w\.\/]/ig, '') : value;
        let displayText = timedValue.length > textOverflowIndex ? timedValue.substr(0, textOverflowIndex) : timedValue;
        if (timedValue.length > textOverflowIndex) danger({ text: `最多输入${textOverflowIndex}个字符!` });
        this.setState({ value: displayText });
        let { onChange } = this.props;
        onChange && onChange(displayText);
    };

    toggleInput = () => {
        this.setState({
            isFormFocus: true
        });
    }

    onBlur = () => {
        this.setState({
            isFormFocus: false
        });
    }

    onFocus = () => {
        this.setState({
            isFormFocus: true
        });
    }

    render() {
        const { editable, autoFocus } = this.props;
        const { value } = this.state;
        const textOverflowIndex = this.state.maxInputStr;
        return (editable ? <div className="editable-edit">
            <div className="editable-edit-container" onClick={this.toggleInput}>
                <FormControl
                    style={{backgroundPositionX : value.replace(/[^\u0000-\u00ff]/g,"aa").length * 10}} // 动态控制icon图标位置显示在文字后
                    autoFocus={autoFocus}
                    onBlur={this.onBlur}
                    onFocus={this.onFocus}
                    className={[
                        " editable-edit-input ", // 数组模式的样式，要在样式前后加空格，否则会引入逗号，导致样式不可用
                        this.state.isFormFocus ? " editable-edit-input-focus " : "",
                        (value.length == textOverflowIndex && this.state.isFormFocus) ? " editable-edit-input-error " : null
                    ]}
                    value={value}
                    onChange={this.handleChange} />
            </div>
        </div> : <div className="editable-browse">{value}</div>)
    }
}

export default StringEditCell;